const Controller = require('egg').Controller;
const fs = require('fs')
const path = require('path')
const pump = require('mz-modules/pump')
// const pinyin = require('pinyin')
let arr = []
function my(i){
    fs.unlink(path.join(i), (err) => {
        if (err) {
            throw err;
        }
        return true;
    });
}
class UploadController extends Controller {
    // 上传图片
    async index() {
        const stream = await this.ctx.getFileStream();
        const filename = new Date().getTime() + path.extname(stream.filename).toLowerCase();
        const target = path.join(this.config.baseDir, 'app/public/uploads', filename);
        const writeStream = fs.createWriteStream(target);
        arr.push(target)
        await pump(stream, writeStream);
        try {
            await this.app.model.Img.create({ image: target })
        } catch {
            console.log('失败');
        }
        let str = '默永';
        this.ctx.body =
        {
            code: 20000,
            data: {
                name: path.join(this.config.baseDir, 'uploads'),
                // file: `/uploads/${filename}` //正式地址
                file: `http://127.0.0.1:7001/uploads/${filename}`  //临时服务器地址
            }
        }
        // console.log(this.ctx.body)
    }
    async get() {
        let data = await this.app.model.Img.findAll()
        for (let i in data) {
            console.log(i);
            await my(data[i].image)
            await this.app.model.Img.destroy({ where: {image:data[i].image} })
        }
        this.ctx.body = data;
    }
}

module.exports = UploadController;